package com.xxl.job.executor.service;

import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.executor.kafka.KafkaProduceService;
import com.xxl.job.executor.model.CurrentInfoHkModel;
import com.xxl.job.executor.model.DevInfosModel;
import com.xxl.job.executor.model.SignalDefHkModel;
import com.xxl.job.executor.repository.CurrentInfoRepository;
import com.xxl.job.executor.utils.ThreadLocalDateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 文件描述
 *
 * @author wang.kunlin
 * @date 2020年03月17日 16:56
 */
@Service
public class AutomaticControlService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AutomaticControlService.class);
    @Autowired
    private SignalDefService signalDefService;
    @Autowired
    private CurrentInfoRepository currentInfoRepository;
    @Autowired
    private KafkaProduceService kafkaProduceService;
    @Autowired
    private BkJsonDataService bkJsonDataService;

    /**
     * 布尔量保存
     *
     * @author wang.kunlin
     * @date 2020年08月19日 16:56
     */
    public void save(SignalDefHkModel automaticControlModel, int flag,ArrayList<DevInfosModel> dataDevModelArrayList){

        List<SignalDefHkModel> queryHkSignalList=signalDefService.queryHkSignalList(

        automaticControlModel.getGatherId(), automaticControlModel.getGatherResId(),automaticControlModel.getPointAddr());
        if(queryHkSignalList==null){
           // LOGGER.error("自控系统：未找到对应的信号配置");
            return;
        }else{
            for (int num = 0; num < queryHkSignalList.size(); num++) {
                String nDate="";
                nDate= ThreadLocalDateUtil.formatDate(new Date());
                String signalType  =queryHkSignalList.get(num).getSignalType();
                //新建实时存储的实体
                CurrentInfoHkModel currentInfoHkModel=new CurrentInfoHkModel();
                currentInfoHkModel.setValue(automaticControlModel.getSignalValue());
                currentInfoHkModel.setGatherResId(automaticControlModel.getGatherResId());
                currentInfoHkModel.setGatherId(automaticControlModel.getGatherId());
                currentInfoHkModel.setDevCode(queryHkSignalList.get(num).getDevCode());
                currentInfoHkModel.setSignalCode(queryHkSignalList.get(num).getCode());
                currentInfoHkModel.setSignalName(queryHkSignalList.get(num).getName());
                currentInfoHkModel.setSignalType(queryHkSignalList.get(num).getSignalType());
                currentInfoHkModel.setValunit(queryHkSignalList.get(num).getValunit());
                currentInfoHkModel.setTime(nDate);
                currentInfoHkModel.setPointAddr(queryHkSignalList.get(num).getPointAddr());
                currentInfoHkModel.setIsSaveEs("1"); // 默认存入es

                //根据实体去redis查询上次信号时间
                CurrentInfoHkModel currentInfoHkModel1=currentInfoRepository.queryHkCurrent(queryHkSignalList.get(num).getDevCode(),queryHkSignalList.get(num).getCode());

                if(currentInfoHkModel1==null){
                    currentInfoHkModel.setLastTime(nDate);
                }else{
                    currentInfoHkModel.setLastTime(currentInfoHkModel1.getTime());

                    if(currentInfoHkModel1.getValue().equals(currentInfoHkModel.getValue())){
                        currentInfoHkModel.setIsSaveEs("0");
                    }
                }
                currentInfoHkModel.setSendTime(ThreadLocalDateUtil.formatDate(new Date()));
                //实时数据存入redis
                boolean isSend=this.isSaveRedis(currentInfoHkModel,currentInfoHkModel1,signalType);
                if(isSend){
                    currentInfoRepository.save(currentInfoHkModel);
                    //发送kafka
                    sends(currentInfoHkModel);

//                    //发送博坤
//                    if(flag==1){
                        DevInfosModel devInfosModel = bkJsonDataService.getDataRealTimeMonitorModel( queryHkSignalList.get(num).getCode(),
                                queryHkSignalList.get(num).getName(),
                                queryHkSignalList.get(num).getSignalType(),
                                queryHkSignalList.get(num).getDevCode(),
                                automaticControlModel.getSignalValue(),
                                queryHkSignalList.get(num).getValunit(),
                                nDate);
                        dataDevModelArrayList.add(devInfosModel);
//                        bkJsonDataService.sendDevInfoMessage(dataDevModelArrayList);
//                    }else{
//                        DevInfosModel devInfosModel = bkJsonDataService.getDataRealTimeMonitorModel( queryHkSignalList.get(num).getCode(),
//                                queryHkSignalList.get(num).getName(),
//                                queryHkSignalList.get(num).getSignalType(),
//                                queryHkSignalList.get(num).getDevCode(),
//                                automaticControlModel.getSignalValue(),
//                                queryHkSignalList.get(num).getValunit(),
//                                nDate);
//                        dataDevModelArrayList.add(devInfosModel);
//                    }

                }

            }


        }

        if(flag==1 && dataDevModelArrayList.size()>0){
            bkJsonDataService.sendDevInfoMessage(dataDevModelArrayList);
        }

    }

    /**
     * 模拟量 INT
     *
     * @author wang.kunlin
     * @date 2020年08月19日 16:56
     */

    public void saves(SignalDefHkModel automaticControlModel, int flag, ArrayList<DevInfosModel> dataDevModelArrayList){
        SignalDefHkModel signalDefHkModel=signalDefService.queryHkSignal(
                automaticControlModel.getGatherId(), automaticControlModel.getGatherResId(),automaticControlModel.getPointAddr());
        if(signalDefHkModel==null){
            // LOGGER.error("自控系统：未找到对应的信号配置");
            return;
        }
        String nDate="";
        nDate= ThreadLocalDateUtil.formatDate(new Date());

        String signalType  =signalDefHkModel.getSignalType();

        //新建实时存储的实体
        CurrentInfoHkModel currentInfoHkModel=new CurrentInfoHkModel();

        currentInfoHkModel.setValue(automaticControlModel.getSignalValue());
        currentInfoHkModel.setGatherResId(automaticControlModel.getGatherResId());
        currentInfoHkModel.setGatherId(automaticControlModel.getGatherId());
        currentInfoHkModel.setDevCode(signalDefHkModel.getDevCode());
        currentInfoHkModel.setSignalCode(signalDefHkModel.getCode());
        currentInfoHkModel.setSignalName(signalDefHkModel.getName());
        currentInfoHkModel.setSignalType(signalDefHkModel.getSignalType());
        currentInfoHkModel.setValunit(signalDefHkModel.getValunit());
        currentInfoHkModel.setTime(nDate);
        currentInfoHkModel.setPointAddr(signalDefHkModel.getPointAddr());
        currentInfoHkModel.setIsSaveEs("1"); // 默认存入es

        //根据实体去redis查询上次信号时间
        CurrentInfoHkModel currentInfoHkModel1=currentInfoRepository.queryHkCurrent(signalDefHkModel.getDevCode(),signalDefHkModel.getCode());

        if(currentInfoHkModel1==null){
            currentInfoHkModel.setLastTime(nDate);
        }else{
            currentInfoHkModel.setLastTime(currentInfoHkModel1.getTime());

            if(currentInfoHkModel1.getValue().equals(currentInfoHkModel.getValue())){
                currentInfoHkModel.setIsSaveEs("0");
            }
        }
        currentInfoHkModel.setSendTime(ThreadLocalDateUtil.formatDate(new Date()));
        //实时数据存入redis
        boolean isSend=this.isSaveRedis(currentInfoHkModel,currentInfoHkModel1,signalType);
        if(isSend){
            currentInfoRepository.save(currentInfoHkModel);
            //发送kafka
            sends(currentInfoHkModel);

            //发送博坤

                DevInfosModel devInfosModel = bkJsonDataService.getDataRealTimeMonitorModel( signalDefHkModel.getCode(),  signalDefHkModel.getName(),
                        signalDefHkModel.getSignalType(),
                        signalDefHkModel.getDevCode(),
                        automaticControlModel.getSignalValue(),
                        signalDefHkModel.getValunit(),
                        nDate);
                dataDevModelArrayList.add(devInfosModel);
//            }else{
//                DevInfosModel devInfosModel = bkJsonDataService.getDataRealTimeMonitorModel( signalDefHkModel.getCode(),  signalDefHkModel.getName(),
//                        signalDefHkModel.getSignalType(),
//                        signalDefHkModel.getDevCode(),
//                        automaticControlModel.getSignalValue(),
//                        signalDefHkModel.getValunit(),
//                        nDate);
//                dataDevModelArrayList.add(devInfosModel);
//            }
        }
         if(flag==1 && dataDevModelArrayList.size()>0){
            bkJsonDataService.sendDevInfoMessage(dataDevModelArrayList);
         }
    }


    /**
     * 发kafka
     * @param message
     */
    public void sends(CurrentInfoHkModel message) {

        try {
            this.kafkaProduceService.sendHkAlarmMessage(message);

        } catch (Exception e) {
            XxlJobLogger.log("发送告警信息失败:"+message.toString(), e);
        }
    }


    /**
     * 布尔量发kafka
     * @param message
     */
    public void send(CurrentInfoHkModel message) {

        try {
            this.kafkaProduceService.sendBLMessage(message);

        } catch (Exception e) {
            XxlJobLogger.log("发送信息失败:"+message.toString(), e);
        }
    }



    /**
     * 判断实时数据是否需要存入redis
     * @param automaticControlStatus
     * @param automaticControlStatus1
     * @return
     */
    private boolean isSaveRedis(CurrentInfoHkModel automaticControlStatus,
                                CurrentInfoHkModel automaticControlStatus1,String signalType){
        int fa = 0;
        long iTimeDiffHour=0;

        if(automaticControlStatus1 != null){
            String autoVal=automaticControlStatus.getValue();
            String oldautoVal=automaticControlStatus1.getValue();
            if(!autoVal.equals(oldautoVal)){

                if(signalType.equals("WD")||signalType.equals("SD") ||signalType.equals("O2") ){//避免值频繁轻微波动
                    iTimeDiffHour = (ThreadLocalDateUtil.parse(automaticControlStatus.getTime()).getTime() - ThreadLocalDateUtil.parse(automaticControlStatus1.getTime()).getTime()) / (1000 * 60* 5);
                    if(iTimeDiffHour<1){
                        double d =Math.abs(Double.valueOf(autoVal) -Double.valueOf (oldautoVal));
                        if(signalType.equals("WD") && d >=1.0){
                            fa =1;
                        }else if(signalType.equals("SD") && d >=3.0){
                            fa =1;

                        }else if(signalType.equals("O2") && d >=0.1){
                            fa =1;
                        }
                    }else{
                        fa =1;
                    }
                }else{
                    fa =1;
                }


            }
            iTimeDiffHour = (ThreadLocalDateUtil.parse(automaticControlStatus.getTime()).getTime() - ThreadLocalDateUtil.parse(automaticControlStatus1.getTime()).getTime()) / (1000 * 60* 60);
        }else{
            iTimeDiffHour = 2;
        }

        if ( fa > 0 || iTimeDiffHour > 1) {
            return true;
        }
        return false;
    }






}

